/* eslint-disable vue/no-v-model-argument */
<template>
    <div class="site-list">
        <!-- 搜索 -->
        <list-filter 
            @search="search"
            :tenant-list="someTenantList"
            :stage-list="stageList"
            :search-area-list="searchAreaList"
        ></list-filter>
        <div class="table-container">
            <div class="operate-btn">
                <el-button v-btn="'midrange:site:list:create'" type="primary" @click="addModel('add')">新建组织站点</el-button>
                <el-button type="primary" @click="viewModel()">预览组织站点结构</el-button>
            </div>
            <!-- 列表 -->
            <table-wrap
                v-if="tableData.length" 
                hideHeader
                :total="total"
                :loading="loading"
                v-model:pageSize="filterForm.pageSize"
                v-model:pageIndex="filterForm.pageIndex"
                @request-list="getList"
                :table-data="tableData"
            >
                <el-table-column label="序号" fixed="left" align="center" show-overflow-tooltip>
                    <template #default="scope">
                        <div>{{(filterForm.pageIndex - 1 )*filterForm.pageSize+scope.$index+1}}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="institutionName" align="center" label="组织名称" min-width="130" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" label="站点版本" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{scope.row.brandBO?.version || '-'}}  
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="dtTenantName" align="center" label="空间名称" min-width="130" show-overflow-tooltip></el-table-column>
                <el-table-column prop="customName" align="center" label="自定义名称" min-width="130" show-overflow-tooltip></el-table-column>
                <el-table-column prop="id" align="center" label="组织ID" min-width="130" show-overflow-tooltip></el-table-column>
                <el-table-column prop="address" align="center" label="所在地区" min-width="130" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{formatAddress(scope.row)}}  
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="institutionType" align="center" label="组织类型" min-width="130" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{institutionObj[scope.row.institutionType]}}  
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="institutionLevel" align="center" label="组织级别" min-width="130" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{institutionLevelObj[scope.row.institutionLevel]}}  
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="institutionAttribute" align="center" label="组织属性" min-width="130" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{institutionAttrObj[scope.row.institutionAttribute]}}  
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="stages" align="center" label="所属学段" min-width="130" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{formatStage(scope.row.stages)}}  
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="subInstitutionCount" align="center" label="下挂组织" min-width="130" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{scope.row.institutionType == 1 ? '-' : scope.row.subInstitutionCount}}  
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="gmtCreate" align="center" label="创建时间" min-width="180" show-overflow-tooltip>
                    <template #default="scope">
                        <span>
                           {{formatTime(scope.row.gmtCreate)}} 
                        </span>
                    </template>
                </el-table-column>
                <el-table-column v-if="showOperate" label="操作" align="center" width="260" fixed="right">
                    <template #default="scope">
                        <el-button v-btn="'midrange:site:list:edit'" link type="primary" @click="addModel('edit', scope.row)">编辑</el-button>
                        <el-button v-btn="'midrange:site:list:userManage'" link type="primary"  @click="userPage(scope.row)">组织用户</el-button>
                        <el-button v-btn="'midrange:site:list:setting'" link type="primary" @click="servicePage(scope.row)">服务设置</el-button>
                        <el-button v-btn="'midrange:site:list:delete'" link type="primary" @click="delSite(scope.row)">删除</el-button>
                        <el-button v-btn="'midrange:site:list:detail'" link type="primary" @click="viewSite(scope.row, 1)">查看</el-button>
                        <el-button v-btn="'midrange:site:list:manageCenter'" link type="primary" @click="viewSite(scope.row, 2)">进入站点管理中心</el-button>
                    </template>
                </el-table-column>
            </table-wrap>
            <no-data v-else></no-data>
        </div>
        <!-- 新增站点dialog -->
        <add-model
            ref="addModelRef"
            :isEdit="isEdit"
            :school-list="schoolList"
            :stage-list="stageList"
            :tenant-list="tenantList"
            :form-data="editForm"
            :template-list="template"
            @remote-school-name="basicSchoolList"
            @submit="submitForm"
        ></add-model>
        <!-- 站点预览dialog -->
        <site-view-model ref="viewModelRef" :tenant-list="someTenantList"></site-view-model>
    </div>
</template>

<script >
import { defineComponent, toRefs, ref, reactive, toRef, computed, onMounted, watch, nextTick } from 'vue'
import Dialog from '@/components/dialogComp.vue'
import tableWrap from '@/components/table-wrap/table-wrap.vue'
import noData from '@/components/no-data.vue'
import listFilter from './part/site-list-filter.vue'
import addModel from './part/site-add-model.vue'
import siteViewModel from './part/site-view-model.vue'
import Fn from '@/lib/fn.js'
import { useStore } from 'vuex';
import { 
    institutionObj,
    institutionLevelObj,
    institutionAttrObj
} from './filter-data.js'
import { formatTimestamp } from '@/lib/tools'
import { useStageList } from '@/hooks/useStageList'
import { useSearchAreaList } from '@/hooks/useSearchAreaList'
import { useBtnAuth } from '@/hooks/useBtnAuth'
import { pageJump } from '@/global/location-transfer';
import { useRoute } from 'vue-router';

const pageBtn = [
    'midrange:site:list:edit',
    'midrange:site:list:userManage',
    'midrange:site:list:setting',
    'midrange:site:list:delete',
    'midrange:site:list:detail',
    'midrange:site:list:manageCenter'
    ]
export default defineComponent({
    name: 'SiteList',
    components: {
        tableWrap,
        noData,
        listFilter,
        addModel,
        siteViewModel
    },
    directives: {
        btn: {
            mounted(el, binding) {
                const {btnAuthMap} = useBtnAuth()
                el.style.display = btnAuthMap.value[binding.value] ? 'initial' : 'none'
            }
        }
    },
    setup(props) {
        const store = useStore();
        const route = useRoute();

        useStageList((data) => (state.stageList = data))
        useSearchAreaList((data) => (state.searchAreaList = data))
        const {getOpBtnLen} = useBtnAuth()
        const formRef = ref(null)
        const areaRef = ref(null)
        const addModelRef = ref(null)
        const viewModelRef = ref(null)
        // 状态数据
        const state = reactive({
            institutionObj,
            institutionLevelObj,
            institutionAttrObj,
            stageList: [], // 学段列表
            filterForm: { // 搜索
                pageIndex: 1,
                pageSize: 10,
                time: ''
            },
            editForm: { // 新增编辑参数
                institutionType: 2,
                areaid: []
            },
            loading: false,
            tableData: [],
            total: 0,
            tenantList: [], // 所有空间列表
            someTenantList: [], // 已创建组织的空间列表
            schoolList: [], // 学校名称列表
            template: [], // 站点模板
            isEdit: 'add',
            searchAreaList: []
        })
        // 计算属性集合
        const comp = {
            showOperate: computed(() => getOpBtnLen(pageBtn))
        }
        // 方法集合
        const fns = {
            // 初始数据
            init(){
                // fns.getList()
                fns.gettenantList()
                fns.templateList()
                fns.tenants()
            },
            formatAddress(row){
                const { provinceName = '', cityName = '', districtName = '' } = row
                return [provinceName, cityName, districtName].filter(item => item != '').join('/')
            },
            // 获取站点模板
            templateList(){
                store.dispatch('proxyAction', {
                    name: 'templateList',
                    message: false,
                    data: {}
                }).then((res) => {
                    state.template = res.data
                    state.editForm.templateId = res.data[0].id
                }).catch(err => {
                    store.dispatch('message', {
                        message: err.message || '操作失败'
                    });
                })
            },
            // 已创建组织的空间
            tenants(){
                store.dispatch('proxyAction', {
                    name: 'institutionTenants',
                    message: false
                }).then((res) => {
                    state.someTenantList = res.data || []
                }).catch(err => {
                    store.dispatch('message', {
                        message: err.message || '操作失败'
                    });
                })
            },
            // 获取所有空间列表
            gettenantList(){
                store.dispatch('proxyAction', {
                    name: 'getTenantSelection',
                    queries: {
                        all: false
                    },
                    message: false
                }).then((res) => {
                    state.tenantList = res.data.map(item => {
                        return {
                            ...item,
                            label: item.tenantName,
                            value: item.tenant
                        }
                    })
                }).catch(err => {
                    store.dispatch('message', {
                        message: err.message || '请求失败'
                    });
                })
            },
            // 获取组织名称
            basicSchoolList(name, type){
                store.dispatch('proxyAction', {
                    name: 'basicSchoolList',
                    message: false,
                    queries: {
                        pageIndex: 1,
                        pageSize: 100,
                        schoolName: name,
                        schoolType: type
                    }
                }).then((res) => {
                    state.schoolList = res.data.rows
                }).catch(err => {
                    store.dispatch('message', {
                        message: err.message || '请求失败'
                    });
                })
            },
            // 格式化时间戳
            formatTime(time){
                return formatTimestamp(time, 'YYYY-MM-DD HH:mm:ss')
            },
            // 格式化学段展示
            formatStage(stage){
                let name = '', stages = stage || []
                stages.length && stages.map((e, i) => {
                    if(i == stages.length -1){
                        name += e.name 
                    } else{
                        name += e.name + ', '
                    }
                })
                return name || '-'
            },
            // 删除站点
            delSite: Fn.Confirm(function({id = ''}){
                store.dispatch('proxyAction', {
                    name: 'manageInstitutionDelete',
                    message: false,
                    queries: {
                        id
                    }
                }).then((res) => {
                    store.dispatch('message', {
                        message: '删除成功'
                    });
                    fns.getList()
                }).catch(err => {
                    console.log(err)
                })
            }, '确认要删除这个站点吗？', '确认删除'),
            // 查看站点
            viewSite(row, type) {
                let domain = row.brandBO && row.brandBO.webDomain || ''
                if(domain){
                    let viewUrl = `https://${domain}/wheat/wand/home?enterType=wand`
                    let adminUrl = `https://${domain}/idxmc`
                        window.open(type == 1 ? viewUrl : adminUrl)
                }else {
                    store.dispatch('message', {
                        message: '请您先配置站点信息再查看'
                    });
                }
            },
            // 保存修改站点
            submitForm(data){
                console.log(data)
                // return
                store.dispatch('proxyAction', {
                    name: 'institutionSave',
                    data: {
                        ...data,
                        areaid: undefined,
                        stageId: undefined,
                        customName: data.customName || data.institutionName,
                        version: 'v2'
                    }
                }).then((res) => {
                    fns.getList()
                    fns.tenants()
                    useSearchAreaList((data) => (state.searchAreaList = data))
                    addModelRef.value.close()
                    store.dispatch('message', {
                        type: 'success',
                        message: '操作成功'
                    });
                }).catch(err => {
                    console.log(err)
                })
            },
            // 跳转组织用户二级页
            userPage(row){
                if(row.institutionState != 1){
                    return store.dispatch('message', {
                                type: 'error',
                                message: '请先配置站点基本信息'
                            });
                }
                store.commit('site/setSiteRoute', {name: row.institutionName, id: row.id});
                pageJump({
                    name: 'siteOrganization',
                    query: {
                        id: row.id,
                        institutionType: row.institutionType,
                        dtTenant: row.dtTenant
                    }
                })
            },
            // 新增修改显示弹窗
            async addModel(type, row = {}){
                state.isEdit = type
                state.schoolList = []
                if(type == 'edit'){
                    state.editForm = row
                }
                await nextTick()
                addModelRef.value.open()
            },
            // 站点预览弹窗
            viewModel(){
                console.log(viewModelRef)
                viewModelRef.value.open()
            },
            // 列表搜索
            search (data){
                state.filterForm = data
                fns.getList()
            },
            // 获取列表
            getList () {
                state.loading = true;
                store.dispatch('proxyAction', {
                    message: false,
                    name: 'siteList',
                    queries: {
                        ...state.filterForm,
                        time: undefined,
                        areaid: undefined,
                        fetchBrand: true,
                        version: 'v2'
                    }
                }).then((res) => {
                    state.tableData = res.data.rows || [];
                    state.total = res.data.total;
                }).catch(err => {
                    store.dispatch('message', {
                        message: err.message || '请求失败'
                    });
                }).finally(() => {
                    state.loading = false;
                })
            },
            // 跳转服务设置页面
            servicePage (row) {
                if(row.brandBO?.version == 'v1'){
                    return store.dispatch('message', {
                                type: 'error',
                                message: '当前站点为1.0，暂时不允许修改'
                            });
                }
                store.commit('site/setSiteRoute', {name: row.institutionName, id: row.id});
                pageJump({
                    name: 'siteService',
                    query: {
                        id: row.id
                    }
                })
            }
        }
        onMounted(() => {
            fns.init()
        })
        return{
            ...toRefs(state),
            ...fns,
            formRef,
            areaRef,
            addModelRef,
            ...comp,
            viewModelRef
        }
    }
})

</script>

<style lang="scss" rel="stylesheet/scss" scoped>
    .site-list{
        padding: 20px;
    }
    .table-container{
        .btns{
            margin-bottom: 10px;
        }
    }
    
    .max{
            height:100px;
            overflow: hidden;
        }
 
</style>
